﻿package com.cenfun.ui{
	import flash.display.*;
	import flash.events.*;
	import flash.utils.*;
	public class BT extends UI {
		public static const BUTTON_DOWN:String = "button_down";
		
		private var bt:SimpleButton;
		private var up:Object;
		private var over:Object;
		private var down:Object;
		
		private var pressTimer:Timer;
		
		private var repeatDelay:Number = 500;
		private var repeatInterval:Number = 35;
		//是否按下重复发送事件
		public var autoRepeat:Boolean = false;
		public function BT(_up:Object = null, _over:Object = null, _down:Object = null):void {
			up = _up;
			over = _over;
			down = _down;
			//
			pressTimer = new Timer(1, 0);
			pressTimer.addEventListener(TimerEvent.TIMER, buttonDown, false, 0, true);
			//
			bt = new SimpleButton();
			bt.useHandCursor = false;
			addChild(bt);
			init();
			//按下事件
			addEventListener(MouseEvent.MOUSE_DOWN, mouseEventHandler, false, 0, true);
			addEventListener(MouseEvent.MOUSE_UP, mouseEventHandler, false, 0, true);
			addEventListener(MouseEvent.ROLL_OUT, mouseEventHandler, false, 0, true);
		}
		
		protected function mouseEventHandler(e:MouseEvent):void {
			if (e.type == MouseEvent.MOUSE_DOWN) {
				startPress();
			} else {
				endPress();
			}
		}
		
		protected function startPress():void {
			if (autoRepeat) {
				pressTimer.delay = repeatDelay;
				pressTimer.start();
			}
			dispatchEvent(new UE(BT.BUTTON_DOWN));
		}
		protected function buttonDown(event:TimerEvent):void {
			if (!autoRepeat) { 
				endPress(); 
				return; 
			}
			if (pressTimer.currentCount == 1) { 
				pressTimer.delay = repeatInterval; 
			}
			dispatchEvent(new UE(BT.BUTTON_DOWN));
		}
		protected function endPress():void {
			pressTimer.reset();
		}
		
		//设置样式
		public function style(o:Object):void {
			if (o) {
				up = o.up;
				over = o.over;
				down = o.down;
			} else {
				up = null;
				over = null;
				down = null;
			}
			init();
		}
		
		public function init():void {
			bt.upState = getDisplayObjectInstance(up);
			bt.overState = bt.hitTestState = getDisplayObjectInstance(over);
			bt.downState = getDisplayObjectInstance(down);
			layout();
		}
		
		
		override public function layout():void {
			if (bt.hitTestState) {
				if (bt.width != tw) {
					bt.width = tw;
				}
				if (bt.height != th) {
					bt.height = th;
				}
			}
		}
		
		
	}
}